<template>
  <el-card style="margin: 20px">
    <el-tree default-expand-all :data="depts" :props="defaultProps">
      <!-- 节点结构 -->
      <!-- v-slot="{ node, data }" 只能作用在template -->
      <template v-slot="{ data }">
        <el-row style="width:100%;height:40px" type="flex" justify="space-between" align="middle">
          <el-col>{{ data.name }}</el-col>
          <el-col :span="6">
            <span class="tree-manager">{{ data.managerName }}</span>
            <!-- $event 实参 表示类型 -->
            <el-dropdown @command="operateDept($event, data)">
              <!-- 显示区域内容 -->
              <span class="el-dropdown-link">
                操作<i class="el-icon-arrow-down el-icon--right" />
              </span>
              <!-- 下拉菜单选项 -->
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                <el-dropdown-item command="del">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>
      </template>
    </el-tree>

    <add-dept ref="addRef" :show-dialog.sync="showDialog" :node="node" @addDeptSuccess="addDeptSuccess" />
  </el-card>

</template>

<script>
import { arrToTree } from '@/utils/index.js'
import { getDepartment, delDepartmentAPI } from '@/api/department'
import AddDept from './AddDept.vue'
export default {
  name: 'Department',
  components: {
    AddDept
  },
  data() {
    return {
      node: {}, // 被点击的节点
      showDialog: false,
      depts: [{
        name: '传智教育',
        children: [
          { name: '总裁办' },
          { name: '行政部' },
          { name: '财务部' }
        ]
      }],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getDeptsData()
  },
  methods: {
    async getDeptsData() {
      const res = await getDepartment()
      this.depts = arrToTree(res, 0)
    },
    async operateDept(type, node) {
      this.node = node
      if (type === 'add') {
        this.showDialog = true
      }
      if (type === 'edit') {
        this.$nextTick(async() => {
          await this.$refs.addRef.getDepartmentDetail(node.id)
        })
        this.showDialog = true
      }
      if (type === 'del') {
        await delDepartmentAPI(node.id)
        this.$message.success('删除成功')
        this.getDeptsData()
      }
    },
    addDeptSuccess() {
      this.getDeptsData()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  width: 80px;
  display: inline-block;
  margin: 10px;
}
</style>
